package ge.tsu.java.project.commons;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleLogger extends Logger {

	private SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss");
	private String tag;
	private String logFile;

	public SimpleLogger(String tag) {
		this.tag = tag;
		logFile = System.getProperty("user.home") + File.separator + "java-project-chat.log";
	}

	@Override
	public void log(String message) {
		System.out.println(tag + " - " + df.format(new Date()));
		System.out.println(message);
	}

	@Override
	public void err(String message) {
		err(message, null);
	}

	@Override
	public void err(Throwable t) {
		err(null, t);
	}

	@Override
	public void err(String message, Throwable t) {
		String logHeader = tag + " - " + df.format(new Date());
		System.err.println(logHeader);
		if (message != null) {
			System.err.println(message);
		}
		if (t != null) {
			System.err.println(t);
			PrintWriter writer = null;
			try {
				writer = new PrintWriter(new FileOutputStream(logFile, true));
				writer.println(logHeader);
				if (message != null) {
					writer.println(message);
				}
				t.printStackTrace(writer);
				writer.println();
				writer.flush();
			} catch (FileNotFoundException e) {
				// ignore
			} finally {
				if (writer != null) {
					writer.close();
				}
			}
		}
	}

	@Override
	public void severe(Throwable t) {
		err(t);
		System.exit(1);
	}

	@Override
	public void severe(String message, Throwable t) {
		err(message, t);
		System.exit(1);
	}

}
